package com.yjd.bi.etl;

import java.util.List;

import org.apache.log4j.Logger;

import com.yjd.bi.report.enums.BiDataChangeRecordStatusEunm;
import com.yjd.bi.report.model.BiDataChangeRecordModel;
import com.yjd.bi.report.service.IBiDataChangeRecordService;
import com.yjd.bi.report.service.IDataChangeRecordDisposeService;
import com.yjd.comm.annotation.ServiceRemoteProxy;
import com.yjd.comm.base.concurrent.task.ITaskHandler;
import com.yjd.comm.base.concurrent.task.ITaskItem;
import com.yjd.comm.base.concurrent.task.TaskDisposeUtil;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.job.BaseJob;
import com.yjd.comm.rpm.RpmServiceKeyEnum;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.vo.IsSuccess;

/**
 * <b>description</b>：处理bi库数据变更日志，根据变更日志将业务库数据迁移至bi库 <br>
 * <b>time</b>：2016-4-8下午3:47:51 <br>
 * <b>author</b>： ready likun_557@163.com
 */
public class BiDataChangeDisposeJob extends BaseJob {

	private Logger logger = Logger.getLogger(BiDataChangeDisposeJob.class);

	@SuppressWarnings("unchecked")
	@Override
	protected boolean doExecute() throws Exception {
		Long curtime = FrameUtil.getTime();
		final IsSuccess isSuccess = new IsSuccess();
		while (true) {
			List<BiDataChangeRecordModel> watiDisposeList = this.biDataChangeRecordService
					.getModelList(FrameUtil.newHashMap(
							"whereSql",
							"(max_failure>failure and status != "
									+ BiDataChangeRecordStatusEunm.SUCCESS
											.getValue()
									+ " and dispose_time <= " + curtime + ")",
							"sort", "id desc"), 0, 1000, DbWREnums.READ);
			if (watiDisposeList.isEmpty()) {
				break;
			} else {
				TaskDisposeUtil.dispose(true, 20, watiDisposeList,
						new ITaskHandler<BiDataChangeRecordModel>() {
							@Override
							public void dispose(
									ITaskItem<BiDataChangeRecordModel> item) {
								try {
									boolean result = BiDataChangeDisposeJob.this.dataChangeRecordDisposeService
											.dispose(item.getItem());
									if (!result) {
										isSuccess.success = result;
									}
								} catch (Exception e) {
									isSuccess.success = false;
									logger.error("全量更新抓取数据日志出错:"
											+ FrameUtil.json(item.getItem()));
									logger.error(
											"全量更新抓取数据日志出错:" + e.getMessage(), e);
								}
							}
						});
			}
		}
		return isSuccess.success;
	}

	@Override
	protected String getJobType() {
		return BiDataChangeDisposeJob.class.getName();
	}

	/**
	 * 数据变更记录服务
	 */
	@ServiceRemoteProxy(serviceUrlResouceKey = RpmServiceKeyEnum.RPM_BI_SERVICE_KEY)
	private IBiDataChangeRecordService biDataChangeRecordService;
	/**
	 * 数据变更记录处理，数据迁移
	 */
	@ServiceRemoteProxy(serviceUrlResouceKey = RpmServiceKeyEnum.RPM_BI_SERVICE_KEY)
	private IDataChangeRecordDisposeService dataChangeRecordDisposeService;

}
